<?php
/**
 * 开发手册参考
 * https://github.com/walkor/phpsocket.io/tree/master/docs/zh
 */
namespace app;
use lib\Http;
use lib\User;
use Workerman\Worker;
use PHPSocketIO\SocketIO;
date_default_timezone_set("Asia/Shanghai");
require_once __DIR__ . '/vendor/autoload.php';
$config=require __DIR__ . '/config.php';

$io = new SocketIO($config['webSocketPort']);
$user=new User($io);
// 监听一个http端口，主要用户允许后台服务器访问的接口（基于http的一个内部RPC服务器）
$io->on('workerStart', function()use($io,$user,$config) {
    $http=new Http($io,$config,$user);
});

// 当有客户端连接时
$io->on('connection', function($socket)use($io,$user){
    $socket->on('login',function($data)use($socket,$user){
        if(!$data)return;
        if(is_string($data)){
            $data=json_decode($data,true);
        }
        if(!isset($data['id'])||!isset($data['login_name'])){  
            $socket->emit('login',[
                'status'=>1,
                'msg'=>'验证数据不能为空!'
            ]);
            $socket->disconnect();
            return;
        }

        // 用户身份验证 (略)
        $socket->member_id=$data['id'];
        if(isset($data['type'])){ //Web 服务器连接
            $socket->type='admin';
            $socket->join($data['id'].'admin');
        }else{
            $socket->type='device';
            $socket->join($data['id']);
        }
        if(isset($data['device_id'])){
            $socket->device_id=$data['device_id'];
            $user->add($socket->id,$data['id'],$data['device_id']);
            
        }
        echo date('Y-m-d H:i:s').' login success... '.json_encode($data)."\r\n";
        $socket->emit('login',[
            'status'=>0,
            'msg'=>'ok'
        ]);
    });

    // 在线用户ID组(来自web服务端)
    $socket->on('getUsers',function($data)use($socket,$user){
        if(isset($socket->type)&&$socket->type==='admin'&&isset($socket->member_id)){
            $user->syncDevices($socket->member_id);
        }
    });

    // 转发客户端事件
    $socket->on('client event',function($data)use($socket){
        if(isset($data['event'])&&strpos($data['event'],'client_')===0){
            $socket->emit($data['event'],$data['data']);
        }
    });

    $socket->on('disconnect',function($err)use($socket,$user){
        if(!isset($socket->member_id)){
            return;
        }
        if(isset($socket->type)&&$socket->type==='device'&&isset($socket->device_id)){
            $user->remove($socket->member_id,$socket->device_id);
            // 同步web服务器用户在线设备
            $user->syncDevices($socket->member_id);
        }
        
    });

    $socket->on('error',function($err)use($socket){
        $socket->disconnect();
        if(!is_string($err)){
            $err=json_encode($err);
        }
        echo 'onError：'.$err."\r\n";
    });
  
});

Worker::runAll();